package cn.wsalix.freemarker;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.Locale;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

import org.springframework.stereotype.Service;

import cn.anlaser.exception.NutException;
import cn.wsalix.biz.form.FreemarkerForm;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

@Service("freemarkerUtil")
public class FreemarkerUtil {
	private static Configuration cfg;

	@PostConstruct
	public void init() {
		cfg = new Configuration(Configuration.VERSION_2_3_22);		
		cfg.setDefaultEncoding("GBK");
		cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
	}

	public void buildFile(FreemarkerForm form) {
		try {
			cfg.setDirectoryForTemplateLoading(new File(form.getTemplateDir()));
			Template temp = cfg.getTemplate(form.getTemplateFile());
			temp.process(form.getParaMap(), form.getOut());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TemplateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public String getCurrDir() {
		return decode(this.getClass().getClassLoader().getResource("")
				.getPath());

	}

	public String decode(String sourCode) {
		return decode(sourCode, Default_charSet);
	}

	public String decode(String sourCode, String enc) throws NutException {
		try {
			return URLDecoder.decode(sourCode, enc);
		} catch (UnsupportedEncodingException e) {
			throw new NutException(e);
		}
	}

	public static String Default_charSet = "UTF-8";
	private static Configuration config = new Configuration();

	/**
	 * @param templateName
	 *            模板名字
	 * @param root
	 *            模板根 用于在模板内输出结果集
	 * @param out
	 *            输出对象 具体输出到哪里
	 */
	public static void processTemplate(String templateName, Map<?, ?> root,
			Writer out) {
		try {
			// 获得模板
			Template template = config.getTemplate(templateName, "utf-8");
			// 生成文件（这里是我们是生成html）
			template.process(root, out);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (TemplateException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				out = null;
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * 初始化模板配置
	 * 
	 * @param servletContext
	 *            javax.servlet.ServletContext
	 * @param templateDir
	 *            模板位置
	 */
	public static void initConfig(ServletContext servletContext,
			String templateDir) {
		config.setLocale(Locale.CHINA);
		config.setDefaultEncoding("utf-8");
		config.setEncoding(Locale.CHINA, "utf-8");
		config.setServletContextForTemplateLoading(servletContext, templateDir);
		config.setObjectWrapper(new DefaultObjectWrapper());
	}
}
